package com.homesoft.runtime.core.loaders;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLClassLoader;

import com.homesoft.runtime.metadata.modle.RootObjectType;

public abstract class MetadataLoader {
	
	private RootObjectType rootObjectType;
	
	/**
	 * 设置元数据对象类型
	 * @param rootObjectType
	 */
	public void setRootObjectType(RootObjectType rootObjectType) {
		this.rootObjectType = rootObjectType;
	}

	/**
	 * 获取元数据对象类型
	 * @return
	 */
	public RootObjectType getRootObjectType() {
		return rootObjectType;
	}

	/**
	 * 获取资源流
	 * @return
	 */
    public abstract InputStream getStream();
    
    /**
     * 资源加载器优先级
     */
    public abstract int getPriority();
    
	/**
	 * 资源来源类型
	 */
    public abstract String getResourceType();
    
	/**
	 * jar包
	 * @param loader
	 * @param resourceName
	 * @return
	 */
    public static MetadataLoader createResourceLoader(URLClassLoader loader, String resourceName) {
    	return new JarMetadataLoader(loader, resourceName);
    }
    
    /**
     * 磁盘文件
     * @param fileFullName
     * @return
     */
    public static MetadataLoader createResourceLoader(String fileFullName) {
        return new FileMetadataLoader(fileFullName);
    }
    
    public static class JarMetadataLoader extends MetadataLoader {
    	
    	private URLClassLoader loader;
        private String resourceName;
        
        public JarMetadataLoader(URLClassLoader loader, String resourceName) {
        	this.loader = loader;
        	this.resourceName = resourceName;
        }
        
		@Override
		public InputStream getStream() {
			return loader.getResourceAsStream(resourceName);
		}

		@Override
		public int getPriority() {
			return 5;
		}

		@Override
		public String getResourceType() {
			return "jar";
		}
    }
    
    private static class FileMetadataLoader extends MetadataLoader {
    	
    	private String fileFullName;
    	
    	public FileMetadataLoader(String fileFullName) {
    		this.fileFullName = fileFullName;
    	}
    	
		@Override
		public InputStream getStream() {
			try {
				File file = new File(this.fileFullName);
				FileInputStream stream = new FileInputStream(file);
				return stream;
			} catch (FileNotFoundException e) {
				return null;
			}
		}

		@Override
		public int getPriority() {
			return 10;
		}

		@Override
		public String getResourceType() {
			return "DiskFile";
		}
    	
    }
}
